#include <iostream>
#include <chrono>
#include <thread>
#include <vector>
#include <memory>
#include <functional>
#include <iomanip>
#include <cassert>
#include <stdexcept>
#include <atomic>

#include "../../include/objPool/objPool.hpp"

// 测试对象类，用于验证对象池功能
class TestObject {
public:
    TestObject(int id = 0, std::string name = "default") 
        : id_(id), name_(name), creation_time_(std::chrono::high_resolution_clock::now()) {
       // std::cout << "TestObject constructed: id=" << id_ << ", name=" << name_ << std::endl;
    }
    
    ~TestObject() {
       // std::cout << "TestObject destroyed: id=" << id_ << ", name=" << name_ << std::endl;
    }
    
    void setValue(int value) {
        value_ = value;
    }
    
    int getValue() const {
        return value_;
    }
    
    int getId() const {
        return id_;
    }
    
    const std::string& getName() const {
        return name_;
    }
    
    void printInfo() const {
        auto now = std::chrono::high_resolution_clock::now();
        auto lifetime = std::chrono::duration_cast<std::chrono::milliseconds>(
            now - creation_time_).count();
        std::cout << "TestObject: id=" << id_ 
                  << ", name=" << name_ 
                  << ", value=" << value_ 
                  << ", lifetime=" << lifetime << "ms" << std::endl;
    }

private:
    int id_;
    std::string name_;
    int value_ = 0;
    std::chrono::high_resolution_clock::time_point creation_time_;
};

// 基本功能测试
void testBasicFunctionality() {
    std::cout << "\n=== 基本功能测试 ===" << std::endl;
    
    // 创建对象池，初始化为5个对象
    wheels::objPool<TestObject> pool(5, 100, "test");
    
    // 测试1: 基本的获取和归还操作
    std::cout << "测试1: 基本获取和归还操作" << std::endl;
    std::vector<TestObject*> objects;
    for (int i = 0; i < 5; ++i) {
        TestObject* obj = pool.get();
        assert(obj != nullptr && "应该成功获取对象");
        obj->setValue(i * 10);
        obj->printInfo();
        objects.push_back(obj);
    }
    
    // 测试2: 池满时获取对象
    std::cout << "\n测试2: 池满时获取对象" << std::endl;
    TestObject* obj6 = pool.get();
    assert(obj6 == nullptr && "池满时应该返回nullptr");
    std::cout << "正确: 对象池已满，无法获取更多对象" << std::endl;
    
    // 测试3: 归还对象后再获取
    std::cout << "\n测试3: 归还对象后再获取" << std::endl;
    pool.release(objects[0]);
    objects.erase(objects.begin());
    
    TestObject* newObj = pool.get();
    assert(newObj != nullptr && "归还一个对象后应该能再次获取");
    std::cout << "成功: 归还一个对象后可以再次获取" << std::endl;
    objects.push_back(newObj);
    
    // 测试4: 归还所有对象
    std::cout << "\n测试4: 归还所有对象" << std::endl;
    for (auto obj : objects) {
        pool.release(obj);
    }
    objects.clear();
    std::cout << "成功: 所有对象已归还" << std::endl;
    
    // 测试5: 批量获取对象
    std::cout << "\n测试5: 批量获取对象" << std::endl;
    for (int i = 0; i < 5; ++i) {
        TestObject* obj = pool.get();
        assert(obj != nullptr && "应该能获取5个对象");
        obj->setValue(i * 100);
        objects.push_back(obj);
    }
    
    // 测试6: 归还无效指针（不应崩溃）
    std::cout << "\n测试6: 归还无效指针" << std::endl;
    TestObject* invalidPtr = nullptr;
    pool.release(invalidPtr); // 应该安全处理
    std::cout << "成功: 安全处理了nullptr归还" << std::endl;
    
    // 清理
    for (auto obj : objects) {
        pool.release(obj);
    }
}

// 性能测试 - 优化版
void testPerformance() {
    std::cout << "\n=== 性能测试 ===" << std::endl;
    
    // 测试配置
    const std::vector<size_t> poolSizes = {100, 1000, 10000};
    const std::vector<int> operationCounts = {100000, 500000, 1000000};
    
    for (const auto& POOL_SIZE : poolSizes) {
        for (const auto& OPERATIONS : operationCounts) {
            std::cout << "\n测试场景: 池大小=" << POOL_SIZE << ", 操作次数=" << OPERATIONS << std::endl;
            
            // 1. 对象池性能测试
            wheels::objPool<TestObject> pool(POOL_SIZE);
            
            auto start = std::chrono::high_resolution_clock::now();
            int successfulGets = 0;
            int failedGets = 0;
            
            std::vector<TestObject*> objects;
            objects.reserve(POOL_SIZE);
            
            for (int i = 0; i < OPERATIONS; ++i) {
                // 获取对象
                TestObject* obj = pool.get();
                if (obj) {
                    obj->setValue(i);
                    objects.push_back(obj);
                    successfulGets++;
                } else {
                    // 如果池为空，归还一些对象
                    if (!objects.empty()) {
                        pool.release(objects.back());
                        objects.pop_back();
                        failedGets++;
                    }
                }
            }
            
            // 归还所有对象
            for (auto obj : objects) {
                pool.release(obj);
            }
            
            auto end = std::chrono::high_resolution_clock::now();
            auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
            double opsPerSec = (successfulGets + failedGets) * 1000000.0 / duration;
            
            std::cout << "  对象池性能: " << std::endl;
            std::cout << "    - 成功获取: " << successfulGets << " 次" << std::endl;
            std::cout << "    - 失败获取: " << failedGets << " 次" << std::endl;
            std::cout << "    - 总耗时: " << duration / 1000.0 << " ms" << std::endl;
            std::cout << "    - 平均每次操作: " << std::fixed << std::setprecision(3) 
                      << (duration * 1.0 / (successfulGets + failedGets)) << " 微秒" << std::endl;
            std::cout << "    - 吞吐量: " << std::fixed << std::setprecision(0) << opsPerSec << " ops/sec" << std::endl;
            
            // 2. 与直接new/delete对比（仅在较小规模测试）
            if (POOL_SIZE <= 100000 && OPERATIONS <= 1000000) {
                std::vector<TestObject*> directObjects;
                directObjects.reserve(POOL_SIZE);
                
                start = std::chrono::high_resolution_clock::now();
                for (int i = 0; i < OPERATIONS; ++i) {
                    if (directObjects.size() < POOL_SIZE) {
                        TestObject* obj = new TestObject(i);
                        obj->setValue(i);
                        directObjects.push_back(obj);
                    } else {
                        // 模拟归还/重用
                        TestObject* obj = directObjects.back();
                        directObjects.pop_back();
                        obj->setValue(i);
                        directObjects.insert(directObjects.begin(), obj);
                    }
                }
                
                // 清理
                for (auto obj : directObjects) {
                    delete obj;
                }
                
                end = std::chrono::high_resolution_clock::now();
                auto directDuration = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
                double directOpsPerSec = OPERATIONS * 1000000.0 / directDuration;
                double speedup = directDuration * 1.0 / duration;
                
                std::cout << "  new/delete性能对比: " << std::endl;
                std::cout << "    - 总耗时: " << directDuration / 1000.0 << " ms" << std::endl;
                std::cout << "    - 平均每次操作: " << std::fixed << std::setprecision(3) 
                          << (directDuration * 1.0 / OPERATIONS) << " 微秒" << std::endl;
                std::cout << "    - 吞吐量: " << std::fixed << std::setprecision(0) << directOpsPerSec << " ops/sec" << std::endl;
                std::cout << "    - 对象池加速比: " << std::fixed << std::setprecision(2) << speedup << "x" << std::endl;
            }
        }
    }
    
    // 3. 长时间运行稳定性测试
    std::cout << "\n长时间运行稳定性测试 (100,000,000次操作):" << std::endl;
    wheels::objPool<TestObject> stabilityPool(1000);
    std::vector<TestObject*> objects;
    objects.reserve(1000);
    
    auto start = std::chrono::high_resolution_clock::now();
    const int STABILITY_OPS = 100000000;
    int interval = STABILITY_OPS / 10;
    
    for (int i = 0; i < STABILITY_OPS; ++i) {
        TestObject* obj = stabilityPool.get();
        if (obj) {
            obj->setValue(i);
            objects.push_back(obj);
        } else if (!objects.empty()) {
            stabilityPool.release(objects.back());
            objects.pop_back();
        }
        
        // 进度报告
        if (i > 0 && i % interval == 0) {
            auto current = std::chrono::high_resolution_clock::now();
            auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(current - start).count();
            std::cout << "  进度: " << (i * 100 / STABILITY_OPS) << "%, 已运行: " << elapsed << "秒" << std::endl;
        }
    }
    
    // 清理
    for (auto obj : objects) {
        stabilityPool.release(obj);
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto stabilityDuration = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
    double stabilityOpsPerSec = STABILITY_OPS * 1.0 / stabilityDuration;
    
    std::cout << "  稳定性测试完成: " << std::endl;
    std::cout << "    - 总操作次数: " << STABILITY_OPS << std::endl;
    std::cout << "    - 总耗时: " << stabilityDuration << " 秒" << std::endl;
    std::cout << "    - 平均吞吐量: " << std::fixed << std::setprecision(0) << stabilityOpsPerSec << " ops/sec" << std::endl;
}

// 并发性能测试
void testConcurrency() {
    std::cout << "\n=== 并发性能测试 ===" << std::endl;
    
    // 测试1: 不同线程数量的性能对比
    std::cout << "\n测试1: 不同线程数量的性能对比" << std::endl;
    const int POOL_SIZE = 100;
    const int OPERATIONS_PER_THREAD = 10000;
    std::vector<int> threadCounts = {1, 2, 4, 8, 16, 32};
     wheels::objPool<TestObject> pool(POOL_SIZE);
        std::atomic<int> successfulOperations(0);
        std::atomic<int> failedOperations(0);
    for (int threadCount : threadCounts) {
       
        
        auto worker = [&pool, &successfulOperations, &failedOperations, threadCount]() {
            for (int i = 0; i < OPERATIONS_PER_THREAD; ++i) {
                TestObject* obj = pool.get();
                if (obj) {
                    // 模拟使用对象
                    obj->setValue(i);
                    successfulOperations++;
                    // 短暂睡眠模拟处理时间
                    std::this_thread::sleep_for(std::chrono::microseconds(5));
                    // 归还对象
                    pool.release(obj);
                } else {
                    // 如果获取失败，记录失败次数
                    failedOperations++;
                    // 短暂等待后重试
                    std::this_thread::sleep_for(std::chrono::microseconds(20));
                }
            }
        };
        
        // 创建并启动线程
        std::vector<std::thread> threads;
        auto start = std::chrono::high_resolution_clock::now();
        
        for (int i = 0; i < threadCount; ++i) {
            threads.emplace_back(worker);
        }
        
        // 等待所有线程完成
        for (auto& t : threads) {
            t.join();
        }
        
        auto end = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
        double throughput = (successfulOperations * 1000.0) / duration; // 每秒操作数
        
        std::cout << "线程数: " << threadCount 
                  << ", 成功操作: " << successfulOperations 
                  << ", 失败操作: " << failedOperations 
                  << ", 耗时: " << duration << "ms"
                  << ", 吞吐量: " << std::fixed << std::setprecision(2) << throughput << " ops/sec" << std::endl;
    }
    
    // 测试2: 高竞争场景测试 - 池大小远小于线程数
    std::cout << "\n\n测试2: 高竞争场景测试 (池大小:20, 线程数:100)" << std::endl;
    {
        const int SMALL_POOL_SIZE = 20;
        const int HIGH_THREAD_COUNT = 100;
        const int HIGH_OPERATIONS = 1000;
        
        wheels::objPool<TestObject> pool(SMALL_POOL_SIZE);
        std::atomic<int> successfulOperations(0);
        std::atomic<int> failedOperations(0);
        
        auto highContentionWorker = [&pool, &successfulOperations, &failedOperations]() {
            for (int i = 0; i < HIGH_OPERATIONS; ++i) {
                TestObject* obj = pool.get();
                if (obj) {
                    // 模拟更短的使用时间，增加竞争
                    obj->setValue(i);
                    successfulOperations++;
                    // 极短的处理时间，增加锁竞争
                    std::this_thread::sleep_for(std::chrono::microseconds(1));
                    pool.release(obj);
                } else {
                    failedOperations++;
                }
            }
        };
        
        std::vector<std::thread> threads;
        auto start = std::chrono::high_resolution_clock::now();
        
        for (int i = 0; i < HIGH_THREAD_COUNT; ++i) {
            threads.emplace_back(highContentionWorker);
        }
        
        for (auto& t : threads) {
            t.join();
        }
        
        auto end = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
        
        std::cout << "高竞争测试完成: " << HIGH_THREAD_COUNT << " 线程，池大小 " << SMALL_POOL_SIZE
                  << ", 成功操作: " << successfulOperations 
                  << ", 失败操作: " << failedOperations
                  << ", 耗时: " << duration << "ms" << std::endl;
    }
    
    // 测试3: 锁粒度测试 - 比较读写操作的并发性能
    std::cout << "\n\n测试3: 读写操作并发性能测试" << std::endl;
    {
        const int LARGE_POOL_SIZE = 1000;
        const int READ_THREADS = 10;
        const int WRITE_THREADS = 2;
        const int READ_OPS = 50000;
        const int WRITE_OPS = 5000;
        
        wheels::objPool<TestObject> pool(LARGE_POOL_SIZE);
        std::atomic<int> successfulGets(0);
        std::atomic<int> successfulReleases(0);
        
        // 读线程（只获取对象并立即归还）
        auto readWorker = [&pool, &successfulGets]() {
            for (int i = 0; i < READ_OPS; ++i) {
                TestObject* obj = pool.get();
                if (obj) {
                    successfulGets++;
                    pool.release(obj);
                }
                // 极小的延迟，模拟高频率获取
                std::this_thread::sleep_for(std::chrono::nanoseconds(100));
            }
        };
        
        // 写线程（获取对象并持有更长时间）
        auto writeWorker = [&pool, &successfulReleases]() {
            for (int i = 0; i < WRITE_OPS; ++i) {
                TestObject* obj = pool.get();
                if (obj) {
                    // 持有对象更长时间，模拟写操作
                    obj->setValue(i * 100);
                    std::this_thread::sleep_for(std::chrono::microseconds(50));
                    pool.release(obj);
                    successfulReleases++;
                }
            }
        };
        
        std::vector<std::thread> threads;
        auto start = std::chrono::high_resolution_clock::now();
        
        // 启动写线程
        for (int i = 0; i < WRITE_THREADS; ++i) {
            threads.emplace_back(writeWorker);
        }
        
        // 启动读线程
        for (int i = 0; i < READ_THREADS; ++i) {
            threads.emplace_back(readWorker);
        }
        
        // 等待所有线程完成
        for (auto& t : threads) {
            t.join();
        }
        
        auto end = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
        
        std::cout << "读写并发测试完成: " << READ_THREADS << " 读线程, " << WRITE_THREADS << " 写线程"
                  << ", 成功获取: " << successfulGets
                  << ", 成功释放: " << successfulReleases
                  << ", 耗时: " << duration << "ms" << std::endl;
    }
    
    // 测试4: 长时间运行的稳定性测试
    std::cout << "\n\n测试4: 长时间运行稳定性测试 (30秒)" << std::endl;
    {
        const int STABILITY_POOL_SIZE = 50;
        const int STABILITY_THREADS = 20;
        const int STABILITY_DURATION_MS = 30000;
        
        wheels::objPool<TestObject> pool(STABILITY_POOL_SIZE);
        std::atomic<int> totalOperations(0);
        std::atomic<bool> shouldStop(false);
        
        auto stabilityWorker = [&pool, &totalOperations, &shouldStop]() {
            while (!shouldStop) {
                TestObject* obj = pool.get();
                if (obj) {
                    obj->setValue(totalOperations);
                    totalOperations++;
                    // 随机处理时间
                    int sleepTime = rand() % 10 + 1; // 1-10微秒
                    std::this_thread::sleep_for(std::chrono::microseconds(sleepTime));
                    pool.release(obj);
                } else {
                    // 如果获取失败，短暂等待
                    std::this_thread::sleep_for(std::chrono::microseconds(10));
                }
            }
        };
        
        std::vector<std::thread> threads;
        
        // 启动线程
        for (int i = 0; i < STABILITY_THREADS; ++i) {
            threads.emplace_back(stabilityWorker);
        }
        
        // 运行指定时间
        std::cout << "开始运行稳定性测试..." << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(STABILITY_DURATION_MS));
        shouldStop = true;
        
        // 等待所有线程完成
        for (auto& t : threads) {
            t.join();
        }
        
        std::cout << "稳定性测试完成: 运行时间 " << STABILITY_DURATION_MS / 1000.0 << "秒"
                  << ", 总操作数: " << totalOperations
                  << ", 平均吞吐量: " << (totalOperations * 1000.0 / STABILITY_DURATION_MS) << " ops/sec" << std::endl;
    }
    
    std::cout << "\n=== 性能优化建议 ===" << std::endl;
    std::cout << "1. 锁机制优化:" << std::endl;
    std::cout << "   - 当前实现中get()和release()方法都使用独占锁，导致高并发下性能瓶颈" << std::endl;
    std::cout << "   - 建议: 考虑使用无锁数据结构或更细粒度的锁策略" << std::endl;
    
    std::cout << "2. 数据结构优化:" << std::endl;
    std::cout << "   - 当前使用std::list存储未使用对象，cache命中率较低" << std::endl;
    std::cout << "   - 建议: 使用std::vector或自定义栈式结构替代std::list以提高cache局部性" << std::endl;
    
    std::cout << "3. 内存管理优化:" << std::endl;
    std::cout << "   - 当前实现中对象创建后一直存在直到池析构" << std::endl;
    std::cout << "   - 建议: 实现动态扩缩容机制，根据实际负载调整池大小" << std::endl;
    
    std::cout << "4. 批处理支持:" << std::endl;
    std::cout << "   - 添加批量获取和释放API，减少锁竞争频率" << std::endl;
    
    std::cout << "5. 无锁队列实现:" << std::endl;
    std::cout << "   - 对于高并发场景，考虑使用无锁队列管理未使用对象" << std::endl;
    std::cout << "   - 如使用std::atomic<type_t*>的栈式结构" << std::endl;
}

// 增加减少对象数量测试
void testIncDecCount() {
    std::cout << "\n=== 增加减少对象数量测试 ===" << std::endl;
    
    // 创建初始大小为3的对象池
    wheels::objPool<TestObject> pool(3, 200, "pool");
    
    // 测试1: 增加对象数量
    std::cout << "测试1: 增加对象数量" << std::endl;
    bool expandResult = pool.incCountTo(8, 300, "expanded");
    assert(expandResult && "应该成功扩展对象池");
    std::cout << "成功扩展对象池到8个对象" << std::endl;
    
    // 测试2: 验证扩展后的获取能力
    std::cout << "\n测试2: 验证扩展后的获取能力" << std::endl;
    std::vector<TestObject*> objects;
    int acquiredCount = 0;
    for (int i = 0; i < 10; ++i) { // 尝试获取10个，应该只能获取8个
        TestObject* obj = pool.get();
        if (obj) {
            acquiredCount++;
            objects.push_back(obj);
            std::cout << "获取对象: id=" << obj->getId() << ", name=" << obj->getName() << std::endl;
        }
    }
    assert(acquiredCount == 8 && "应该能获取8个对象");
    std::cout << "成功: 获取了预期的" << acquiredCount << "个对象" << std::endl;
    
    // 测试3: 边界情况 - 增加到更小的数量
    std::cout << "\n测试3: 边界情况 - 增加到更小的数量" << std::endl;
    expandResult = pool.incCountTo(5); // 比当前数量小
    assert(expandResult && "增加到更小数量应该返回成功但不执行实际操作");
    
    // 测试4: 边界情况 - 增加到无效数量
    std::cout << "测试4: 边界情况 - 增加到无效数量" << std::endl;
    expandResult = pool.incCountTo(-1); // 无效数量
    assert(!expandResult && "增加到无效数量应该返回失败");
    
    // 归还部分对象（以便能减少数量）
    for (size_t i = 0; i < objects.size() / 2; ++i) {
        pool.release(objects[i]);
    }
    objects.resize(objects.size() / 2);
    
    // 测试5: 减少对象数量
    std::cout << "\n测试5: 减少对象数量" << std::endl;
    bool shrinkResult = pool.decCountTo(5);
    assert(shrinkResult && "应该成功减少对象池");
    std::cout << "成功将对象池减少到5个对象" << std::endl;
    
    // 测试6: 边界情况 - 减少到无效数量
    std::cout << "测试6: 边界情况 - 减少到无效数量" << std::endl;
    shrinkResult = pool.decCountTo(-1);
    assert(!shrinkResult && "减少到无效数量应该返回失败");
    
    // 测试7: 尝试在对象都在使用时减少数量（应该失败）
    std::cout << "\n测试7: 尝试在对象都在使用时减少数量" << std::endl;
    // 先获取所有可用对象
    std::vector<TestObject*> tempObjects;
    TestObject* obj;
    while ((obj = pool.get()) != nullptr) {
        tempObjects.push_back(obj);
    }
    
    // 尝试减少到比当前使用对象更少的数量
    shrinkResult = pool.decCountTo(1);
    assert(!shrinkResult && "当所有对象都在使用时，减少数量应该失败");
    std::cout << "正确: 当所有对象都在使用时，减少数量失败" << std::endl;
    
    // 归还临时对象
    for (auto tempObj : tempObjects) {
        pool.release(tempObj);
    }
    
    // 测试8: 归还剩余对象
    std::cout << "\n测试8: 归还剩余对象" << std::endl;
    for (auto obj : objects) {
        pool.release(obj);
    }
    objects.clear();
    
    // 测试9: 收缩内存池
    std::cout << "\n测试9: 收缩内存池" << std::endl;
    bool fitResult = pool.shrinkToFit();
    assert(fitResult && "收缩内存池应该成功");
    std::cout << "成功收缩内存池" << std::endl;
    
    // 测试10: 清空对象池
    std::cout << "\n测试10: 清空对象池" << std::endl;
    pool.clear();
    std::cout << "对象池已清空" << std::endl;
    
    // 验证清空后无法获取对象
    TestObject* clearedObj = pool.get();
    assert(clearedObj == nullptr && "清空后应该无法获取对象");
    std::cout << "正确: 清空后无法获取对象" << std::endl;
}

// 对象生命周期测试（内存泄漏检测）
void testObjectLifecycle() {
    std::cout << "\n=== 对象生命周期测试（内存泄漏检测）===" << std::endl;
    
    // 测试1: 基本构造析构计数测试
    std::cout << "\n测试1: 基本构造析构计数测试" << std::endl;
    {
        // 使用静态计数器追踪对象创建和销毁
        static std::atomic<int> constructorCount(0);
        static std::atomic<int> destructorCount(0);
        
        // 临时测试类用于检测构造和析构
        class LifecycleObject {
        public:
            LifecycleObject() {
                constructorCount++;
            }
            
            ~LifecycleObject() {
                destructorCount++;
            }
        };
        
        // 重置计数器
        constructorCount = 0;
        destructorCount = 0;
        
        std::cout << "创建对象池（5个对象）" << std::endl;
        {   
            wheels::objPool<LifecycleObject> pool(5);
            std::cout << "对象池初始化后 - 构造函数调用: " << constructorCount << "次" << std::endl;
            std::cout << "对象池初始化后 - 析构函数调用: " << destructorCount << "次" << std::endl;
            
            // 获取和归还对象测试
            std::cout << "\n获取所有对象" << std::endl;
            std::vector<LifecycleObject*> objects;
            for (int i = 0; i < 5; ++i) {
                objects.push_back(pool.get());
            }
            std::cout << "获取对象后 - 构造函数调用: " << constructorCount << "次" << std::endl;
            std::cout << "获取对象后 - 析构函数调用: " << destructorCount << "次" << std::endl;
            
            std::cout << "\n归还所有对象" << std::endl;
            for (auto obj : objects) {
                pool.release(obj);
            }
            std::cout << "归还对象后 - 构造函数调用: " << constructorCount << "次" << std::endl;
            std::cout << "归还对象后 - 析构函数调用: " << destructorCount << "次" << std::endl;
            
            std::cout << "\n清空对象池" << std::endl;
            pool.clear();
            std::cout << "清空对象池后 - 构造函数调用: " << constructorCount << "次" << std::endl;
            std::cout << "清空对象池后 - 析构函数调用: " << destructorCount << "次" << std::endl;
        }
        
        std::cout << "\n对象池销毁后 - 构造函数调用: " << constructorCount << "次" << std::endl;
        std::cout << "对象池销毁后 - 析构函数调用: " << destructorCount << "次" << std::endl;
        
        if (constructorCount != destructorCount) {
            std::cout << "警告: 构造函数和析构函数调用次数不匹配！内存可能泄漏！" << std::endl;
            std::cout << "构造次数 - 析构次数 = " << (constructorCount - destructorCount) << " 个对象未销毁" << std::endl;
        }
    }
    
    // 测试2: 增加和减少对象数量时的生命周期管理
    std::cout << "\n\n测试2: 增加和减少对象数量时的生命周期管理" << std::endl;
    {
        static std::atomic<int> constructorCount(0);
        static std::atomic<int> destructorCount(0);
        
        class CountedObject {
        public:
            CountedObject(int id = 0) : id_(id) {
                constructorCount++;
                // std::cout << "构造 CountedObject " << id_ << std::endl;
            }
            
            ~CountedObject() {
                destructorCount++;
                // std::cout << "析构 CountedObject " << id_ << std::endl;
            }
            
            int getId() const { return id_; }
            
        private:
            int id_;
        };
        
        constructorCount = 0;
        destructorCount = 0;
        
        std::cout << "创建初始大小为3的对象池" << std::endl;
        wheels::objPool<CountedObject> pool(3, 100);
        std::cout << "初始池 - 构造函数调用: " << constructorCount << "次" << std::endl;
        
        std::cout << "\n扩展对象池到8个对象" << std::endl;
        pool.incCountTo(8, 200);
        std::cout << "扩展后 - 构造函数调用: " << constructorCount << "次" << std::endl;
        
        // 获取部分对象，使部分对象处于使用状态
        std::cout << "\n获取3个对象" << std::endl;
        std::vector<CountedObject*> objects;
        for (int i = 0; i < 3; ++i) {
            objects.push_back(pool.get());
        }
        
        std::cout << "\n减少对象池到5个对象" << std::endl;
        pool.decCountTo(5);
        std::cout << "减少后 - 构造函数调用: " << constructorCount << "次" << std::endl;
        std::cout << "减少后 - 析构函数调用: " << destructorCount << "次" << std::endl;
        
        std::cout << "\n归还所有对象" << std::endl;
        for (auto obj : objects) {
            pool.release(obj);
        }
        
        std::cout << "\n再次减少对象池到2个对象" << std::endl;
        pool.decCountTo(2);
        std::cout << "再次减少后 - 析构函数调用: " << destructorCount << "次" << std::endl;
        
        std::cout << "\n执行shrinkToFit" << std::endl;
        pool.shrinkToFit();
        std::cout << "shrinkToFit后 - 析构函数调用: " << destructorCount << "次" << std::endl;
        
        std::cout << "\n执行clear" << std::endl;
        pool.clear();
        std::cout << "clear后 - 析构函数调用: " << destructorCount << "次" << std::endl;
        
        std::cout << "\n总结 - 构造: " << constructorCount << "次, 析构: " << destructorCount << "次" << std::endl;
        std::cout << "差异: " << (constructorCount - destructorCount) << "个对象未销毁" << std::endl;
    }
    
    // 测试3: 内存使用统计测试（简单模拟）
    std::cout << "\n\n测试3: 内存使用统计测试" << std::endl;
    {
        // 模拟一个需要较多内存的对象
        class MemoryIntensiveObject {
        public:
            MemoryIntensiveObject() {
                data = new char[1024 * 1024]; // 1MB
                for (int i = 0; i < 1024 * 1024; i++) {
                    data[i] = i % 256; // 初始化数据
                }
            }
            
            ~MemoryIntensiveObject() {
                delete[] data;
            }
            
        private:
            char* data;
        };
        
        std::cout << "创建大型对象池测试（注意观察内存使用）" << std::endl;
        std::cout << "1. 初始状态" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(2)); // 给用户时间观察
        
        {   
            std::cout << "\n2. 创建10个1MB对象的对象池" << std::endl;
            wheels::objPool<MemoryIntensiveObject> pool(10);
            std::cout << "对象池创建完成，预计使用约10MB内存" << std::endl;
            std::this_thread::sleep_for(std::chrono::seconds(3));
            
            std::cout << "\n3. 获取所有对象" << std::endl;
            std::vector<MemoryIntensiveObject*> objects;
            for (int i = 0; i < 10; ++i) {
                objects.push_back(pool.get());
            }
            std::this_thread::sleep_for(std::chrono::seconds(2));
            
            std::cout << "\n4. 归还所有对象" << std::endl;
            for (auto obj : objects) {
                pool.release(obj);
            }
            std::this_thread::sleep_for(std::chrono::seconds(2));
            
            std::cout << "\n5. 调用clear()" << std::endl;
            pool.clear();
            std::cout << "注意: 即使调用clear()，由于未调用析构函数，内存仍可能不会释放" << std::endl;
            std::this_thread::sleep_for(std::chrono::seconds(3));
        }
        
        std::cout << "\n6. 对象池销毁" << std::endl;
        std::cout << "注意: 即使对象池销毁，由于未调用对象析构函数，内存可能仍然泄漏" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(3));
    }
    
    // 总结报告
    std::cout << "\n\n=== 内存泄漏检测测试总结 ===" << std::endl;
    std::cout << "1. 关键问题: objPool当前实现没有在以下情况调用对象析构函数:" << std::endl;
    std::cout << "   - 调用decCountTo()减少对象数量时" << std::endl;
    std::cout << "   - 调用clear()清空对象池时" << std::endl;
    std::cout << "   - 对象池自身析构时" << std::endl;
    std::cout << "2. 风险: 对于包含动态分配内存或其他资源的对象，这会导致严重的内存泄漏和资源泄露" << std::endl;
    std::cout << "3. 建议修复方案:" << std::endl;
    std::cout << "   - 在decCountTo()中移除对象前调用析构函数" << std::endl;
    std::cout << "   - 在clear()中清空列表前调用所有对象的析构函数" << std::endl;
    std::cout << "   - 在objPool析构函数中调用所有剩余对象的析构函数" << std::endl;
}

// 异常场景测试
void testExceptionScenarios() {
    std::cout << "\n=== 异常场景测试 ===" << std::endl;
    
    // 测试1: 池耗尽场景测试
    std::cout << "\n测试1: 池耗尽场景测试" << std::endl;
    {
        std::cout << "创建容量为3的对象池" << std::endl;
        wheels::objPool<TestObject> pool(3);
        
        std::cout << "获取所有可用对象..." << std::endl;
        std::vector<TestObject*> objects;
        for (int i = 0; i < 3; ++i) {
            objects.push_back(pool.get());
            std::cout << "  成功获取对象" << std::endl;
        }
        
        std::cout << "尝试获取额外对象（池已耗尽）..." << std::endl;
        try {
            // 当前实现中，池耗尽时会返回nullptr
            TestObject* extraObj = pool.get();
            if (extraObj == nullptr) {
                std::cout << "  结果: 返回nullptr（符合预期）" << std::endl;
            } else {
                std::cout << "  警告: 池耗尽时返回了有效对象，这可能不符合预期行为" << std::endl;
                objects.push_back(extraObj);
            }
        } catch (const std::exception& e) {
            std::cout << "  错误: 抛出异常: " << e.what() << std::endl;
        }
        
        // 清理
        std::cout << "\n归还对象到池中..." << std::endl;
        for (auto obj : objects) {
            pool.release(obj);
        }
    }
    
    // 测试2: 无效对象归还测试
    std::cout << "\n\n测试2: 无效对象归还测试" << std::endl;
    {
        wheels::objPool<TestObject> pool(3);
        
        std::cout << "测试1: 归还非池对象" << std::endl;
        try {
            TestObject* invalidObj = new TestObject();
            std::cout << "  尝试归还非池对象..." << std::endl;
            pool.release(invalidObj);
            std::cout << "  警告: 允许归还非池对象，可能导致内存错误" << std::endl;
            delete invalidObj; // 防止内存泄漏
        } catch (const std::exception& e) {
            std::cout << "  错误: 抛出异常: " << e.what() << std::endl;
        }
        
        std::cout << "\n测试2: 重复归还同一对象" << std::endl;
        try {
            TestObject* obj = pool.get();
            std::cout << "  第一次归还对象..." << std::endl;
            pool.release(obj);
            std::cout << "  第二次归还同一对象..." << std::endl;
            pool.release(obj);
            std::cout << "  警告: 允许重复归还对象，可能导致对象重复加入池" << std::endl;
        } catch (const std::exception& e) {
            std::cout << "  错误: 抛出异常: " << e.what() << std::endl;
        }
        
        std::cout << "\n测试3: 归还nullptr" << std::endl;
        try {
            std::cout << "  尝试归还nullptr..." << std::endl;
            pool.release(nullptr);
            std::cout << "  警告: 允许归还nullptr，可能导致无效状态" << std::endl;
        } catch (const std::exception& e) {
            std::cout << "  错误: 抛出异常: " << e.what() << std::endl;
        }
    }
    
    // 测试3: 内存不足模拟测试
    std::cout << "\n\n测试3: 内存不足模拟测试" << std::endl;
    {
        std::cout << "测试创建大对象池" << std::endl;
        try {
            // 创建一个非常大的对象池尝试触发内存分配失败
            // 注意: 这个测试可能会导致程序崩溃或系统响应缓慢
            // 因此我们使用一个相对安全的值
            size_t largeSize = 10000; // 10,000个对象
            
            std::cout << "  尝试创建包含" << largeSize << "个大型对象的池..." << std::endl;
            
            // 创建一个需要大量内存的对象
            class LargeObject {
            public:
                LargeObject() {
                    data = new char[1024 * 1024]; // 1MB
                }
                
                ~LargeObject() {
                    delete[] data;
                }
            private:
                char* data;
            };
            
            wheels::objPool<LargeObject> largePool(largeSize);
            std::cout << "  成功: 创建了大型对象池" << std::endl;
            
        } catch (const std::bad_alloc& e) {
            std::cout << "  预期行为: 内存分配失败: " << e.what() << std::endl;
        } catch (const std::exception& e) {
            std::cout << "  错误: 抛出异常: " << e.what() << std::endl;
        }
    }
    
    // 测试4: 线程安全异常处理
    std::cout << "\n\n测试4: 线程安全异常处理" << std::endl;
    {
        wheels::objPool<TestObject> pool(5);
        std::atomic<bool> exceptionOccurred(false);
        
        // 创建一个可能抛出异常的任务函数
        auto riskyTask = [&pool, &exceptionOccurred](int threadId) {
            try {
                // 随机操作序列
                for (int i = 0; i < 100; ++i) {
                    // 故意创建竞争条件
                    TestObject* obj = nullptr;
                    
                    if (rand() % 2 == 0) {
                        obj = pool.get();
                    }
                    
                    // 模拟随机的小延迟
                    std::this_thread::sleep_for(std::chrono::microseconds(rand() % 10));
                    
                    if (obj != nullptr) {
                        pool.release(obj);
                    }
                }
            } catch (const std::exception& e) {
                std::cout << "  线程" << threadId << "异常: " << e.what() << std::endl;
                exceptionOccurred = true;
            }
        };
        
        std::cout << "创建10个线程执行并发操作..." << std::endl;
        std::vector<std::thread> threads;
        for (int i = 0; i < 10; ++i) {
            threads.emplace_back(riskyTask, i);
        }
        
        for (auto& t : threads) {
            t.join();
        }
        
        if (exceptionOccurred) {
            std::cout << "  警告: 多线程操作期间发生异常" << std::endl;
        } else {
            std::cout << "  成功: 多线程操作期间未发生异常" << std::endl;
        }
    }
    
    // 测试5: 边界条件测试
    std::cout << "\n\n测试5: 边界条件测试" << std::endl;
    {
        std::cout << "测试1: 创建零大小池" << std::endl;
        try {
            wheels::objPool<TestObject> zeroPool(0);
            std::cout << "  警告: 允许创建零大小池，后续get()操作将始终返回nullptr" << std::endl;
            
            TestObject* obj = zeroPool.get();
            if (obj == nullptr) {
                std::cout << "  验证: get()返回nullptr（预期行为）" << std::endl;
            }
        } catch (const std::exception& e) {
            std::cout << "  错误: 抛出异常: " << e.what() << std::endl;
        }
        
        std::cout << "\n测试2: 负参数测试" << std::endl;
        try {
            wheels::objPool<TestObject> negPool(-5);
            std::cout << "  警告: 允许创建负数大小池，可能导致未定义行为" << std::endl;
        } catch (const std::exception& e) {
            std::cout << "  错误: 抛出异常: " << e.what() << std::endl;
        }
        
        std::cout << "\n测试3: incCountTo和decCountTo边界测试" << std::endl;
        try {
            wheels::objPool<TestObject> pool(5);
            
            std::cout << "  测试incCountTo负数..." << std::endl;
            pool.incCountTo(-3);
            std::cout << "  警告: 允许incCountTo负数，可能导致未定义行为" << std::endl;
            
            std::cout << "  测试decCountTo负数..." << std::endl;
            pool.decCountTo(-3);
            std::cout << "  警告: 允许decCountTo负数，可能导致未定义行为" << std::endl;
            
        } catch (const std::exception& e) {
            std::cout << "  错误: 抛出异常: " << e.what() << std::endl;
        }
    }
    
    // 异常测试总结
    std::cout << "\n\n=== 异常场景测试总结 ===" << std::endl;
    std::cout << "1. 关键问题:" << std::endl;
    std::cout << "   - 池耗尽时返回nullptr而非抛出异常，可能导致空指针访问" << std::endl;
    std::cout << "   - 允许归还非池对象、重复归还和nullptr，可能导致内存错误" << std::endl;
    std::cout << "   - 缺少参数验证，允许负数大小池的创建" << std::endl;
    std::cout << "   - 内存分配失败处理不完善" << std::endl;
    std::cout << "\n2. 建议改进:" << std::endl;
    std::cout << "   - 添加参数验证，拒绝负数和无效参数" << std::endl;
    std::cout << "   - 在池耗尽时提供配置选项（返回nullptr或抛出异常）" << std::endl;
    std::cout << "   - 实现对象所有权跟踪，防止重复归还和非法对象归还" << std::endl;
    std::cout << "   - 完善内存分配失败的错误处理机制" << std::endl;
    std::cout << "   - 添加适当的异常安全保证" << std::endl;
}

// 测试结果统计类
class TestStatistics {
public:
    static TestStatistics& getInstance() {
        static TestStatistics instance;
        return instance;
    }
    
    void addPassedTest(const std::string& testName) {
        passedTests.push_back(testName);
    }
    
    void addFailedTest(const std::string& testName, const std::string& reason) {
        failedTests.push_back({testName, reason});
    }
    
    void addWarning(const std::string& testName, const std::string& warning) {
        warnings.push_back({testName, warning});
    }
    
    void printSummary() {
        std::cout << "\n\n" << std::string(80, '=') << std::endl;
        std::cout << "           OBJPOOL 测试框架 - 测试结果汇总            " << std::endl;
        std::cout << std::string(80, '=') << std::endl;
        
        std::cout << "\n测试结果: ";
        if (failedTests.empty()) {
            std::cout << "✅ 全部通过" << std::endl;
        } else {
            std::cout << "❌ 部分失败" << std::endl;
        }
        
        std::cout << "\n通过的测试 (" << passedTests.size() << "): " << std::endl;
        for (const auto& test : passedTests) {
            std::cout << "  ✅ " << test << std::endl;
        }
        
        std::cout << "\n失败的测试 (" << failedTests.size() << "): " << std::endl;
        if (failedTests.empty()) {
            std::cout << "  无" << std::endl;
        } else {
            for (const auto& [test, reason] : failedTests) {
                std::cout << "  ❌ " << test << ": " << reason << std::endl;
            }
        }
        
        std::cout << "\n警告 (" << warnings.size() << "): " << std::endl;
        if (warnings.empty()) {
            std::cout << "  无" << std::endl;
        } else {
            for (const auto& [test, warning] : warnings) {
                std::cout << "  ⚠️ " << test << ": " << warning << std::endl;
            }
        }
        
        std::cout << "\n" << std::string(80, '=') << std::endl;
    }
    
private:
    std::vector<std::string> passedTests;
    std::vector<std::pair<std::string, std::string>> failedTests;
    std::vector<std::pair<std::string, std::string>> warnings;
    
    TestStatistics() = default;
    ~TestStatistics() = default;
    
    TestStatistics(const TestStatistics&) = delete;
    TestStatistics& operator=(const TestStatistics&) = delete;
};

// 输出测试环境信息
void printEnvironmentInfo() {
    std::cout << std::string(80, '=') << std::endl;
    std::cout << "           OBJPOOL 测试框架 - 环境信息               " << std::endl;
    std::cout << std::string(80, '=') << std::endl;
    
    // 获取当前时间
    auto now = std::chrono::system_clock::now();
    std::time_t now_time = std::chrono::system_clock::to_time_t(now);
    std::tm* local_time = std::localtime(&now_time);
    
    char time_buffer[80];
    std::strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%d %H:%M:%S", local_time);
    
    std::cout << "测试时间: " << time_buffer << std::endl;
    
    // 打印C++标准信息
    std::cout << "C++标准: C++";
#if defined(__cplusplus)
    if (__cplusplus == 202002L) std::cout << "20";
    else if (__cplusplus == 201703L) std::cout << "17";
    else if (__cplusplus == 201402L) std::cout << "14";
    else if (__cplusplus == 201103L) std::cout << "11";
    else if (__cplusplus == 199711L) std::cout << "98";
    else std::cout << "未知 (" << __cplusplus << ")";
#else
    std::cout << "未知";
#endif
    std::cout << std::endl;
    
    // 打印平台信息
    std::cout << "平台信息: ";
#ifdef _WIN32
    std::cout << "Windows";
#elif defined(__linux__)
    std::cout << "Linux";
#elif defined(__APPLE__)
    std::cout << "macOS";
#else
    std::cout << "未知";
#endif
    std::cout << std::endl;
    
    // 获取处理器核心数
    unsigned int cores = std::thread::hardware_concurrency();
    std::cout << "CPU核心数: " << (cores > 0 ? cores : 0) << " 核心" << std::endl;
    
    std::cout << std::string(80, '=') << "\n" << std::endl;
}

// 测试执行器 - 包装测试函数执行并捕获异常
void runTest(const std::string& testName, const std::function<void()>& testFunc) {
    std::cout << "\n🔹 开始执行测试: " << testName << std::endl;
    std::cout << std::string(60, '-') << std::endl;
    
    auto start_time = std::chrono::high_resolution_clock::now();
    
    try {
        testFunc();
        
        auto end_time = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
        
        std::cout << std::string(60, '-') << std::endl;
        std::cout << "✅ 测试完成: " << testName << " (耗时: " << duration.count() << "ms)" << std::endl;
        
        TestStatistics::getInstance().addPassedTest(testName);
    } catch (const std::exception& e) {
        auto end_time = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
        
        std::cout << std::string(60, '-') << std::endl;
        std::cout << "❌ 测试失败: " << testName << " (耗时: " << duration.count() << "ms)" << std::endl;
        std::cout << "  异常: " << e.what() << std::endl;
        
        TestStatistics::getInstance().addFailedTest(testName, std::string("异常: ") + e.what());
    } catch (...) {
        auto end_time = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
        
        std::cout << std::string(60, '-') << std::endl;
        std::cout << "❌ 测试失败: " << testName << " (耗时: " << duration.count() << "ms)" << std::endl;
        std::cout << "  异常: 未知异常" << std::endl;
        
        TestStatistics::getInstance().addFailedTest(testName, "未知异常");
    }
}

// 整合所有测试用例的函数
void runAllTests() {
    // 基本测试组
    runTest("基本功能测试", testBasicFunctionality);
    runTest("增减对象数量测试", testIncDecCount);
    
    // 性能测试组
    runTest("性能测试", testPerformance);
    runTest("并发性能测试", testConcurrency);
    
    // 健壮性测试组
    runTest("内存泄漏检测测试", testObjectLifecycle);
    runTest("异常场景测试", testExceptionScenarios);
}

int main() {
    // 初始化随机数种子
    std::srand(static_cast<unsigned int>(std::time(nullptr)));
    
    // 打印测试框架信息
    std::cout << "欢迎使用 Wheels::objPool 测试框架" << std::endl;
    std::cout << "此框架用于全面测试对象池的功能、性能和健壮性\n" << std::endl;
    
    // 打印环境信息
    printEnvironmentInfo();
    
    // 执行所有测试
    try {
        runAllTests();
    } catch (...) {
        std::cout << "\n❌ 测试框架发生严重错误" << std::endl;
    }
    
    // 打印测试总结
    TestStatistics::getInstance().printSummary();
    
    // 打印objPool实现的主要问题总结
    std::cout << "\n\n" << std::string(80, '=') << std::endl;
    std::cout << "                 OBJPOOL 实现状态总结                 " << std::endl;
    std::cout << std::string(80, '=') << std::endl;
    
    std::cout << "1. ✅ 已修复的问题:" << std::endl;
    std::cout << "   - 修复了memPond.hpp中析构函数的内存管理逻辑错误" << std::endl;
    std::cout << "   - 确认了allocator.hpp中使用空删除器的正确性（避免重复释放）" << std::endl;
    
    std::cout << "\n2. 🔴 待解决的严重问题:" << std::endl;
    std::cout << "   - 并发控制逻辑错误（get()方法使用共享锁修改数据）" << std::endl;
    std::cout << "   - 缺乏对象所有权跟踪，允许非法对象归还" << std::endl;
    
    std::cout << "\n3. 🟠 中等问题:" << std::endl;
    std::cout << "   - 锁粒度过粗，可能导致并发性能瓶颈" << std::endl;
    std::cout << "   - 池耗尽时返回nullptr，缺乏配置选项" << std::endl;
    std::cout << "   - 缺少参数验证和错误处理" << std::endl;
    
    std::cout << "\n4. 🟡 轻微问题:" << std::endl;
    std::cout << "   - 没有提供内存使用统计和监控" << std::endl;
    std::cout << "   - 缺少详细的调试信息" << std::endl;
    std::cout << "   - 建议添加更多的单元测试覆盖边界情况" << std::endl;
    
    std::cout << "\n" << std::string(80, '=') << "\n" << std::endl;
    std::cout << "测试完成！" << std::endl;
    
    return 0;
}